/*
 * @# AlbumLikeServiceImpl.java 2011-12-30 下午04:03:08
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.album.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.ianswer.common.orm.PublicDao;
import com.ianswer.common.util.time.SecondsUtils;
import com.ianswer.px.album.entity.AlbumLike;
import com.ianswer.px.album.redis.AlbumRedis;
import com.ianswer.px.album.service.AlbumLikeService;
import com.ianswer.px.user.entity.UserBaseInfo;

/**
 * @author alvin hwang
 */
@Service("albumLikeService")
public class AlbumLikeServiceImpl implements AlbumLikeService {

	@Resource(name = "publicDao")
	private PublicDao publicDao;
	
	@Override
	public List<AlbumLike> queryFirstPage(Long albumId) {
		return query(albumId, 1);
	}

	@Override
	public List<AlbumLike> query(Long albumId, int pageIndex) {
		AlbumLike cond = new AlbumLike();
		cond.setAlbumId(albumId);
		cond.setPageIndex(pageIndex);
		List<AlbumLike> likes = publicDao.query("albumsLikes.queryByPage", cond);
		if (CollectionUtils.isEmpty(likes)) {
			return new ArrayList<AlbumLike>();
		}
		for (AlbumLike like : likes) {
			Long userId = like.getUserId();
			like.setUser(UserBaseInfo.get(userId));
		}
		return likes;
	}

	@Override
	public Long insert(Long albumId, Long userId) {
		AlbumLike like = new AlbumLike();
		like.setAlbumId(albumId);
		like.setUserId(userId);
		like.setCreatedAt(SecondsUtils.seconds());
		like.setPageIndex(calPageIndex(albumId));
		
		Long likeId = (Long) publicDao.insert("albumsLikes.insert", like);
		
		AlbumRedis.incrLikes(albumId);
		
		return likeId;
	}

	private int calPageIndex(Long albumId) {
		return (AlbumRedis.likes(albumId) + 1) / RESULTS_PER_PAGE + 1;
	}
}
